<template>
  <el-dialog 
    v-model="createWorkVisible" 
    title="添加作业" 
    width="600px"
    @closed="handleDialogClose"
  >
    <el-form 
      ref="createWorkForm"
      :model="createWorkForm" 
      :rules="formRules"
      label-width="100px"
      class="work-form"
    >
      <!-- 文件上传 -->
      <el-form-item>
        <el-upload 
          action="" 
          :http-request="onCreateUpload"
          :limit="1"
        >
          <el-button 
            size="small" 
            type="primary"
          >
            <i class="el-icon-upload2" /> 导入作业
          </el-button>
        </el-upload>
      </el-form-item>

      <!-- 基础信息部分 -->
      <el-form-item 
        label="作业类型" 
        prop="type"
      >
        <el-radio-group v-model="createWorkForm.type">
          <el-radio 
            :label="1"
          >
            个人作业
          </el-radio>
          <el-radio 
            :label="2"
          >
            小组作业
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item 
        label="作业标题" 
        prop="title"
      >
        <el-input 
          v-model="createWorkForm.title"
          maxlength="70"
          show-word-limit
          placeholder="请输入作业标题"
        />
      </el-form-item>

      <el-form-item 
        label="作业描述" 
        prop="content"
      >
        <el-input 
          v-model="createWorkForm.content"
          type="textarea"
          :rows="4"
          placeholder="请输入作业描述"
        />
      </el-form-item>

      <el-form-item 
        label="活动类型" 
        prop="activity"
      >
        <el-input 
          v-model="createWorkForm.activity"
          maxlength="10"
          show-word-limit
        />
      </el-form-item>

      <!-- 选择项部分 -->
      <el-form-item 
        label="应用环节" 
        prop="process"
      >
        <el-select 
          v-model="createWorkForm.process"
          placeholder="请选择应用环节"
        >
          <el-option 
            v-for="item in processOptions"
            :key="item.value"
            v-bind="item"
          />
        </el-select>
      </el-form-item>

      <el-form-item 
        label="所属章节" 
        prop="chapter"
      >
        <el-select 
          v-model="createWorkForm.chapter"
          placeholder="请选择所属章节"
        >
          <el-option 
            v-for="item in chapter"
            :key="item.value"
            v-bind="item"
          />
        </el-select>
      </el-form-item>

      <!-- 发布设置 -->
      <el-form-item>
        <el-switch
          v-model="createWorkMoreVisible"
          active-text="立即发布"
        />
      </el-form-item>

      <!-- 发布详细设置 -->
      <template v-if="createWorkMoreVisible">
        <el-form-item 
          label="发布时间" 
          prop="releaseTime"
        >
          <el-date-picker
            v-model="createWorkForm.releaseTime"
            type="datetime"
            placeholder="选择发布时间"
          />
        </el-form-item>

        <el-form-item 
          label="截止时间" 
          prop="endTime"
        >
          <el-date-picker
            v-model="createWorkForm.endTime"
            type="datetime"
            placeholder="选择截止时间"
          />
        </el-form-item>

        <el-form-item 
          label="总分" 
          prop="score"
        >
          <div class="score-setting">
            <el-input
              v-model.number="createWorkForm.score"
              type="number"
              placeholder="请输入总分"
            />
            <el-switch
              v-model="TimeoutVisible"
              active-text="超时禁止提交"
            />
          </div>
        </el-form-item>
      </template>
    </el-form>

    <template #footer>
      <el-button 
        @click="handleCancel"
      >
        取 消
      </el-button>
      <el-button 
        type="primary" 
        @click="handleSubmit"
      >
        确 定
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getFormData } from "@/tools/getFormData.js";
import { formatDateTime } from '@/utils/date';
import { post } from "@/utils/request";
// import { post } from "@/utils/request";
import Storage from "@/utils/storage";

export default {
    name: "AddWork",
    emits: ['success', 'init'],

    data() {
        return {
            createWorkVisible: false,
            createWorkMoreVisible: false,
            TimeoutVisible: false,
            createWorkForm: {
                activity: "作业",
                type: null,
                title: '',
                content: '',
                process: null,
                chapter: null,
                releaseTime: null,
                endTime: null,
                score: null
            },
            processOptions: [
                { label: '课前', value: 0 },
                { label: '课中', value: 1 },
                { label: '课后', value: 2 },
                { label: '期中', value: 3 },
                { label: '期末', value: 4 }
            ],
            chapter: []
        }
    },

    computed: {
        formRules() {
            const rules = {
                type: [{ required: true, message: '请选择作业类型' }],
                title: [{ required: true, message: '请输入作业标题' }],
                process: [{ required: true, message: '请选择应用环节' }],
                // chapter: [{ required: true, message: '请选择所属章节' }]
            }

            if (this.createWorkMoreVisible) {
                rules.releaseTime = [{ required: true, message: '请选择发布时间' }]
                rules.endTime = [{ required: true, message: '请选择截止时间' }]
                rules.score = [
                    { required: true, message: '请输入总分' },
                    { type: 'number', message: '总分必须为数字' }
                ]
            }

            return rules
        }
    },

    methods: {
        show() {
            this.createWorkVisible = true
      },
      isAddWorkVisible() {
      this.show();
    },
        createWork() {
    if (this.$refs.addWorkInfo && typeof this.$refs.addWorkInfo.show === "function") {
      this.$refs.addWorkInfo.show();
    } else {
      console.error("AddWork component is not available or 'show' method is missing");
    }
  },
        handleCancel() {
            this.$refs.createWorkForm.resetFields()
            this.createWorkVisible = false
            this.createWorkMoreVisible = false
        },

        async handleSubmit() {
            try {
                await this.$refs.createWorkForm.validate()
              const formData = this.prepareFormData()
                console.log(formData)
                await this.submitWork(formData)
                this.$emit('success')
                this.handleCancel()
            } catch (error) {
                console.error('表单提交失败:', error)
            }
        },

        prepareFormData() {
            const formData = { ...this.createWorkForm }
            
            if (this.createWorkMoreVisible) {
                formData.status = 2
                formData.releaseTime = formatDateTime(formData.releaseTime)
                formData.endTime = formatDateTime(formData.endTime)
                formData.isAllowOvertimeSubmission = this.TimeoutVisible ? 2 : 1
            } else {
                formData.status = 1
                delete formData.releaseTime
                delete formData.endTime
                formData.score = 0
            }

            formData.courseId = Storage.getSession("currentCourseMember").id
            return formData
        },

      async submitWork(formData) {
        console.log(formData);
        console.log(getFormData(formData))
        const res= post('api/work/insert', formData
        // {
        //   courseId: formData.courseId,
        //   type: formData.type,
        //   title: formData.title,
        //   content: formData.content,
        //   endTime: formData.endTime,
        //   releaseTime: formData.releaseTime,
        //   score: formData.score
        //   }
        );
          console.log(res);
            if (res) {
                this.$emit('init')
            }
            return res
        },

        onCreateUpload(file) {
            this.createWorkForm.workFile = file.file
        },

        handleDialogClose() {
            this.handleCancel()
        }
    }
}
</script>

<style scoped lang="less">
.work-form {
    .score-setting {
        display: flex;
        align-items: center;
        gap: 20px;

        .el-input {
            width: 220px;
        }
    }
}
</style>
